import sys
sys.path.append("../reading_data")



import time
import datetime as dt

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.dates import date2num
from matplotlib.dates import num2date

from read_from_h5 import load_data


def plot_power(data_tab):
    """
    Simple plotting of the power distribution over a one year period
    """
    start_day=dt.datetime(2011,01,01)
    stop_day=dt.datetime(2012,01,01)
    r1 = range(0,2100,100)
    r2 = range(100,2200,100)
    rs = zip(r1, r2)
    fig, axs = plt.subplots(1,1)
    ax = axs
    dats = []
    for low, high in rs:
        over_filter = ["(ActivePowerAvg >= " + str(low) + ")",
                       "(ActivePowerAvg <" + str(high) + ")"]
        time_filt = ["(Time > " + str(date2num(start_day)) + ")"]
        time_filt += ["(Time < " + str(date2num(stop_day)) + ")"]
        filt = over_filter + time_filt
        dat = get_data.filter_h5data(data_tab, filt)
        dats.append(float(len(dat)))
    total_dats = sum(dats)
    ax.bar(r1, [dat / total_dats * 100 for dat in dats ], width = 50)
    ax.set_title("Power Distribution")
    return

def plot_gear_temp(data):
    colors = ("#FEE5D9", "#FCAE91", "#FB6A4A", "#CB181D",)
    start_pow = 100
    stop_pow = 2000
    step_pow = 500
    r1 = range(start_pow, stop_pow, step_pow)
    r2 = range(start_pow + step_pow, stop_pow + step_pow, step_pow)
    rs = zip(r1, r2)
    low = 200
    high = 2000
    fig, axs = plt.subplots(1,1)
    ax = axs
    for i, (low, high) in list(enumerate(rs)):
        dat1 = data[np.where(data['activepoweravg'] >= low)]
        dat = dat1[np.where(dat1['activepoweravg'] < high)]
        print low
        print high
        print " Mean: ",
        print np.mean(dat["gearbeartempavg"]),
        print " Variance: ",
        print np.var(dat["gearbeartempavg"])
        ax.plot(num2date(dat["time"]), dat["gearbeartempavg"], 'o', ms=6,
                label=str(int(float(low)/2000*100)) + '-' + str(int(float(high)/2000*100)) + "%", color=colors[i], markeredgewidth=0.1)#markeredgecolor=colors[i])
    #ax.set_title("Gear bearing temperature at different power levels")
    #ax.set_title("Plot of raw data")
    ax.set_ylabel("Gear bearing temperature [$^\circ$C]")
    axs.spines['top'].set_visible(False)
    axs.spines['right'].set_visible(False)
    axs.get_xaxis().tick_bottom()
    axs.get_yaxis().tick_left()
    ax.legend(loc=3, fancybox=True)
    fig.autofmt_xdate()

def plot_yaw_angle(turbines, data):
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122, sharex=ax1)
    for turb in turbines:
        dat = data[np.where(data["turbid"]==turb)]
        ax1.plot(num2date(dat["time"]), dat["winddirabsoluteavg"], 'o', ms=6, alpha=0.5)
        ax2.plot(num2date(dat["time"]), dat["winddirrelativeavg"], 'o', ms=6, label=turb)
    ax2.legend(loc=3, fancybox=True)
    fig.autofmt_xdate()
    return


def get_data_from_turbines(turbines):
    filt_strings = ["(activepoweravg > 100)",
                    "(activepoweravg < 2200)",
                    "(time >= " + \
                    str(date2num(dt.datetime(2008, 01, 01))) + ")",
                    "(time <= " + \
                    str(date2num(dt.datetime(2011, 04, 01))) + ")"]
    h5_file = "../../bindata/wh1.h5"
    turb_string = []
    for turb in turbines:
        turb_string.append("(turbid == '" + turb + "')")
    or_string = "( " + " | ".join(turb_string) + " )"
    print or_string
    filt_strings.append(or_string)
    data = load_data(h5_file, filt=filt_strings)
    return data

def look_at_direction():
    start_time = time.time()
    turbines = "WH1105", "WH1106", "WH1107", "WH1108", "WH1115", "WH1116", "WH1117", "WH1118", "WH1225", "WH1226", "WH1227", "WH1228",
    data = get_data_from_turbines(turbines)
    print len(data[np.where(data["turbid"]=="WH1108")]["winddirrelativeavg"])
    print len(data[np.where(data["turbid"]=="WH1107")]["winddirrelativeavg"])
    plot_yaw_angle(turbines, data)
    print "Done in:",
    print (time.time() - start_time)
    plt.show()


def look_at_it():
    start_time = time.time()
    turbines = "WH1227",
    data = get_data_from_turbines(turbines)
    print data['activepoweravg']
    plot_gear_temp(data)
    #plot_power(data_sets[0])
    print "Done in:",
    print (time.time() - start_time)
    plt.show()

def main():
    look_at_direction()
    return

if __name__=='__main__':
    main()
